import axios, { type Method } from 'axios'
import { showToast } from 'vant'
import { useUserStore } from '@/stores'
import router from '@/router'
//基地址
const baseURL = import.meta.env.VITE_BASE_development_URL

const instance = axios.create({
  baseURL,
  timeout: 5000
})

instance.interceptors.request.use(
  (config) => {
    const store = useUserStore()

    if (store.user?.token && config.headers) {
      config.headers.Authorization = `Bearer ${store.user?.token}`
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

instance.interceptors.response.use(
  (res) => {
    if (res.data.code !== 10000) {
      showToast(res.data?.message || '业务失败')
      return Promise.reject(res.data)
    }
    return res.data
  },
  (error) => {
    //处理401过期token
    if (error.response.status === 401) {
      const store = useUserStore()
      store.delUser()
      router.push({
        path: '/login',
        query: {
          returnUrl: router.currentRoute.value.fullPath
        }
      })
    }
    return Promise.reject(error)
  }
)

type Data<T> = {
  code: number
  message: string
  data: T
}

const request = async <T>(url: string, method?: Method , data?: object) => {
  !method &&( method = 'get')
  return instance<T, Data<T>>({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: data
  })
}

export { baseURL, instance, request }
